//
//  UserAccountViewModel.swift
//  weibo
//
//  Created by apple on 15/12/15.
//  Copyright © 2015年 LYR. All rights reserved.
//

import UIKit
import AFNetworking


//  封装网络请求  和 业务逻辑
class UserAccountViewModel: NSObject {

//    定义 UserAccount 模型 的属性
    let userAccount: UserAccount?
    
//    定义用户是否登录的标记
    var userLogin: Bool {
       
    return (userAccount?.access_token) != nil
        
    }
    
    // 定义用户名
    var userName: String? {
    
    return userAccount?.name
    }
    
    //定义用户头像的URL
    var headImgURL: NSURL? {
    
        let url = NSURL(string: userAccount?.avatar_large ?? "")
        return url
    }
    
    //token
    var access_token: String? {
    
    return userAccount?.access_token
        
    }
    
    override init() {
        
       //  初始化 userAccount  （先构造本类  再构造父类）
        userAccount = UserAccount.loadAccount()
        
        super.init()
        
    }
    // MARK:加载用户token(请求标识)
    func loadAccessToken(code: String, finished:(isSuccess: Bool) -> () ) {
        
      //  发送请求的URL
        let urlString = "oauth2/access_token"
        
       // 发送请求要用到的参数
        let dict = ["client_id":client_id,"client_secret":client_secret,"grant_type":"authorization_code","code":code,"redirect_uri":redirect_uri]
        
        NetworkTools.sharedTools.requestJSONDict(.POST, urlString: urlString, parameters: dict) { (dict, error) -> () in
            
            if error != nil {
              // 请求失败 的回调
            finished(isSuccess: false)
            return
            }
            //KVC 字典转模型
            let userAccount = UserAccount(dict: dict!)
            self.getInfoWithAccount(userAccount, finished: finished)
            
        }
        
    }

//   MARK:根据access token 来获取用户信息
    func getInfoWithAccount(account: UserAccount, finished:(isSuccess: Bool)->()) {
        
          let urlString = "2/users/show.json"
        
        if let token = account.access_token, userId = account.uid {
        
            let parameters = ["access_token": token,"uid": userId]
            
            NetworkTools.sharedTools.requestJSONDict(.GET, urlString: urlString, parameters: parameters, finished: { (dict, error) -> () in
                
                if error != nil {
                    // 请求失败 的回调
                    finished(isSuccess: false)
                    return
                }
                
               // 获取用户名称、头像
                let name = dict!["name"] as! String
                
                let avatar_large = dict!["avatar_large"] as! String
                
             // 给acount name、avatar_large 属性赋值
                account.name = name
                
                account.avatar_large = avatar_large
                
              //  存储自定义对象
                account.saveAccount()
                
             // 程序走到这里 说明已经获取到了用户信息
                finished(isSuccess: true)

            })
            
        }
        
    }

}




